{% extends 'base.html' %}
{% load static %}

{% block title %}{{ post.title }} - 本地有约{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row">
        <!-- 帖子内容 -->
        <div class="col-lg-8">
            <!-- 帖子头部 -->
            <div class="card mb-4">
                <div class="card-body">
                    <!-- 导航 -->
                    <nav aria-label="breadcrumb" class="mb-4">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="{% url 'location:community_home' %}">社区</a></li>
                            <li class="breadcrumb-item"><a href="{% url 'location:community_posts' %}">帖子列表</a></li>
                            <li class="breadcrumb-item active">帖子详情</li>
                        </ol>
                    </nav>

                    <!-- 帖子标题和元信息 -->
                    <div class="mb-4">
                        <h1 class="h2 mb-3">{{ post.title }}</h1>
                        <div class="d-flex flex-wrap align-items-center text-muted mb-3">
                            <div class="d-flex align-items-center me-4">
{#                                <img src="{{ post.author.avatar.url|default:'/static/images/default-avatar.jpg' }}"#}
{#                                     class="rounded-circle me-2" width="32" height="32" alt="头像">#}
                                <div>
                                    <a href="{% url 'location:user_profile' post.author.id %}" class="text-decoration-none">
                                        <strong class="text-dark">{{ post.author.username }}</strong>
                                    </a>
                                    <div class="small">发布于 {{ post.created_at|timesince }}前</div>
                                </div>
                            </div>
                            <div class="d-flex flex-wrap gap-2">
                                <span class="badge bg-primary">{{ post.get_post_type_display }}</span>
                                {% if post.event %}
                                <a href="{% url 'location:activity_detail' post.event.id %}" class="badge bg-info text-decoration-none">
                                    {{ post.event.category.name }}活动
                                </a>
                                {% endif %}
                                {% if post.is_pinned %}
                                <span class="badge bg-warning">置顶</span>
                                {% endif %}
                                {% if post.is_featured %}
                                <span class="badge bg-success">精选</span>
                                {% endif %}
                            </div>
                        </div>

                        <!-- 统计信息 -->
                        <div class="d-flex align-items-center text-muted small">
                            <span class="me-3"><i class="fas fa-eye me-1"></i>{{ post.views_count }} 浏览</span>
                            <span class="me-3"><i class="fas fa-comment me-1"></i><span id="totalCommentsCount">{{ post.comments_count }}</span> 评论</span>
                            <span class="me-3"><i class="fas fa-heart me-1"></i>{{ post.likes_count }} 点赞</span>
                            {% if post.updated_at != post.created_at %}
                            <span class="me-3"><i class="fas fa-edit me-1"></i>编辑于 {{ post.updated_at|timesince }}前</span>
                            {% endif %}
                        </div>
                    </div>

                    <!-- 帖子内容 -->
                    <div class="post-content mb-4">
                        {{ post.content|linebreaks|safe }}
                    </div>

                    <!-- 互动按钮 -->
                    <div class="d-flex justify-content-between align-items-center border-top pt-4">
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-danger" id="likeButton" onclick="togglePostLike({{ post.id }})">
                                <i class="fas fa-heart {% if user_liked %}text-danger{% endif %}" id="likeIcon"></i>
                                <span id="likeCount">{{ post.likes_count }}</span> 点赞
                            </button>
                            <button class="btn btn-outline-primary" onclick="scrollToComments()">
                                <i class="fas fa-comment"></i> 评论
                            </button>
                            <button class="btn btn-outline-secondary" onclick="sharePost()">
                                <i class="fas fa-share"></i> 分享
                            </button>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-h"></i>
                            </button>
                            <ul class="dropdown-menu">
                                {% if user.is_authenticated and user != post.author %}
                                <li>
                                    <a class="dropdown-item" href="#" onclick="reportPost({{ post.id }})">
                                        <i class="fas fa-flag me-2"></i>举报
                                    </a>
                                </li>
                                {% endif %}
                                {% if user.is_authenticated and user == post.author %}
                                <li>
                                    <a class="dropdown-item" href="{% url 'location:edit_post' post.id %}">
                                        <i class="fas fa-edit me-2"></i>编辑
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item text-danger" href="#" onclick="deletePost({{ post.id }})">
                                        <i class="fas fa-trash me-2"></i>删除
                                    </a>
                                </li>
                                {% endif %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 评论区域 -->
            <div class="card" id="commentsSection">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-comments me-2"></i>评论
                        <span class="badge bg-primary ms-2" id="commentsBadge">{{ post.comments_count }}</span>
                    </h5>
                </div>
                <div class="card-body">
                    <!-- 评论表单 -->
                    {% if user.is_authenticated %}
                    <div class="comment-form mb-4">
                        <form id="commentForm" onsubmit="addComment(event, {{ post.id }})">
                            {% csrf_token %}
                            <div class="mb-3">
                                <textarea class="form-control" id="commentContent" name="content"
                                          rows="3" placeholder="写下你的评论..." required></textarea>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">支持 Markdown 语法</small>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane me-2"></i>发表评论
                                </button>
                            </div>
                        </form>
                    </div>
                    {% else %}
                    <div class="alert alert-info text-center">
                        <a href="{% url 'customer:login' %}" class="btn btn-primary me-2">登录</a>
                        后即可发表评论
                    </div>
                    {% endif %}

                    <!-- 评论列表 -->
                    <div id="commentsList">
                        {% for comment in comments %}
                        <div class="comment-item mb-4 pb-4 border-bottom" id="comment-{{ comment.id }}">
                            <div class="d-flex align-items-start">
                                <img src="{{ comment.author.avatar.url|default:'/static/images/default-avatar.jpg' }}"
                                     class="rounded-circle me-3" width="40" height="40" alt="头像">
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <div>
                                            <a href="{% url 'location:user_profile' comment.author.id %}" class="text-decoration-none">
                                                <strong class="text-dark">{{ comment.author.username }}</strong>
                                            </a>
                                            <small class="text-muted ms-2">{{ comment.created_at|timesince }}前</small>
                                        </div>
                                        <div class="d-flex gap-1">
                                            <!-- 点赞按钮 -->
                                            <button class="btn btn-sm btn-outline-danger" onclick="likeComment({{ comment.id }})">
                                                <i class="fas fa-heart"></i>
                                                <span id="commentLikeCount-{{ comment.id }}">{{ comment.likes_count }}</span>
                                            </button>
                                            <!-- 回复按钮 -->
                                            <button class="btn btn-sm btn-outline-primary" onclick="replyToComment({{ comment.id }}, '{{ comment.author.username }}')">
                                                <i class="fas fa-reply"></i> 回复
                                            </button>
                                            <!-- 删除按钮（仅评论作者可见） -->
                                            {% if user.is_authenticated and user == comment.author %}
                                            <button class="btn btn-sm btn-outline-danger" onclick="deleteComment({{ comment.id }})">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                            {% endif %}
                                        </div>
                                    </div>

                                    <div class="comment-content mb-2">
                                        {{ comment.content|linebreaks }}
                                    </div>

                                    <!-- 回复表单 -->
                                    <div class="reply-form mt-3 d-none" id="replyForm-{{ comment.id }}">
                                        <form onsubmit="addReply(event, {{ post.id }}, {{ comment.id }})">
                                            {% csrf_token %}
                                            <div class="mb-2">
                                                <textarea class="form-control form-control-sm" name="content"
                                                          rows="2" placeholder="回复 @{{ comment.author.username }}..." required></textarea>
                                            </div>
                                            <div class="d-flex justify-content-between align-items-center">
                                                <small class="text-muted">按 Enter 发送</small>
                                                <div>
                                                    <button type="button" class="btn btn-sm btn-secondary me-2"
                                                            onclick="cancelReply({{ comment.id }})">取消</button>
                                                    <button type="submit" class="btn btn-sm btn-primary">回复</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>

                                    <!-- 回复列表 -->
                                    <div id="replies-{{ comment.id }}">
                                        {% for reply in comment.replies.all %}
                                        <div class="reply-item mt-3 ms-4 ps-3 border-start" id="comment-{{ reply.id }}">
                                            <div class="d-flex align-items-start">
{#                                                <img src="{{ reply.author.avatar.url|default:'/static/images/default-avatar.jpg' }}"#}
{#                                                     class="rounded-circle me-2" width="32" height="32" alt="头像">#}
                                                <div class="flex-grow-1">
                                                    <div class="mb-1">
                                                        <a href="{% url 'location:user_profile' reply.author.id %}" class="text-decoration-none">
                                                            <strong class="text-dark">{{ reply.author.username }}</strong>
                                                        </a>
                                                        <small class="text-muted ms-2">回复 {{ comment.author.username }}</small>
                                                        <small class="text-muted ms-2">{{ reply.created_at|timesince }}前</small>
                                                    </div>
                                                    <div class="small">
                                                        {{ reply.content|linebreaks }}
                                                    </div>
                                                    <div class="mt-1">
                                                        <button class="btn btn-sm btn-outline-danger" onclick="likeComment({{ reply.id }})">
                                                            <i class="fas fa-heart"></i>
                                                            <span id="commentLikeCount-{{ reply.id }}">{{ reply.likes_count }}</span>
                                                        </button>
                                                        {% if user.is_authenticated and user == reply.author %}
                                                        <button class="btn btn-sm btn-outline-danger ms-1" onclick="deleteComment({{ reply.id }})">
                                                            <i class="fas fa-trash"></i> 删除
                                                        </button>
                                                        {% endif %}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% empty %}
                        <div class="text-center py-4">
                            <i class="fas fa-comment-slash fa-2x text-muted mb-3"></i>
                            <p class="text-muted">暂无评论，快来发表第一条评论吧！</p>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="col-lg-4">
            <!-- 作者信息 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-user me-2"></i>作者信息</h6>
                </div>
                <div class="card-body text-center">
                    <img src="{{ post.author.avatar.url|default:'/static/images/default-avatar.jpg' }}"
                         class="rounded-circle mb-3" width="80" height="80" alt="头像">
                    <h5>{{ post.author.username }}</h5>
                    <p class="text-muted small mb-3">{{ post.author.bio|default:"这个用户很懒，什么都没写..." }}</p>

                    <div class="row text-center mb-3">
                        <div class="col-4">
                            <div class="h6 mb-1">{{ post.author.organized_events.count }}</div>
                            <small class="text-muted">发起活动</small>
                        </div>
                        <div class="col-4">
                            <div class="h6 mb-1">{{ post.author.community_posts.count }}</div>
                            <small class="text-muted">发布帖子</small>
                        </div>
                        <div class="col-4">
                            <div class="h6 mb-1">{{ followers_count }}</div>
                            <small class="text-muted">粉丝</small>
                        </div>
                    </div>

                    <div class="d-grid gap-2">
                        <a href="{% url 'location:user_profile' post.author.id %}" class="btn btn-outline-primary">
                            查看主页
                        </a>
                        {% if user.is_authenticated and user != post.author %}
                        <button class="btn btn-primary" id="followButton" onclick="toggleFollow({{ post.author.id }})">
                            <i class="fas fa-plus me-2"></i>关注
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 相关帖子 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-link me-2"></i>
                        {% if post.event %}
                        相关帖子
                        {% else %}
                        相关帖子
                        {% endif %}
                        <span class="badge bg-secondary ms-2">{{ related_posts|length }}</span>
                    </h6>
                </div>
                <div class="card-body p-0">
                    {% for related_post in related_posts %}
                    <div class="p-3 {% if not forloop.last %}border-bottom{% endif %}">
                        <h6 class="small mb-1">
                            <a href="{% url 'location:post_detail' related_post.id %}" class="text-decoration-none text-dark">
                                {{ related_post.title }}
                            </a>
                        </h6>
                        <div class="d-flex justify-content-between align-items-center text-muted smaller">
                            <div class="d-flex align-items-center">
                                <span class="me-2">{{ related_post.author.username }}</span>
                                <span class="mx-1">•</span>
                                <span>{{ related_post.created_at|timesince }}前</span>
                            </div>
                            <div class="d-flex align-items-center gap-2">
                                <small>
                                    <i class="fas fa-eye me-1"></i>{{ related_post.views_count }}
                                </small>
                                <small>
                                    <i class="fas fa-comment me-1"></i>{{ related_post.comments_count }}
                                </small>
                            </div>
                        </div>
                        {% if related_post.event %}
                        <div class="mt-1">
                            <span class="badge bg-light text-dark border smaller">
                                <i class="fas fa-calendar-alt me-1"></i>
                                {{ related_post.event.title|truncatechars:15 }}
                            </span>
                        </div>
                        {% endif %}
                    </div>
                    {% empty %}
                    <div class="text-center py-4">
                        <i class="fas fa-file-alt fa-2x text-muted mb-2"></i>
                        <p class="text-muted small mb-0">
                            {% if post.event %}
                            该活动暂无其他帖子
                            {% else %}
                            暂无相关帖子
                            {% endif %}
                        </p>
                    </div>
                    {% endfor %}
                </div>
            </div>

            <!-- 活动信息 -->
            {% if post.event %}
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-calendar-alt me-2"></i>关联活动</h6>
                </div>
                <div class="card-body">
                    <h6 class="mb-2">{{ post.event.title }}</h6>
                    <p class="text-muted small mb-2">
                        <i class="fas fa-map-marker-alt me-1"></i>{{ post.event.location }}
                    </p>
                    <p class="text-muted small mb-3">
                        <i class="fas fa-clock me-1"></i>{{ post.event.start_time|date:"m月d日 H:i" }}
                    </p>
                    <a href="{% url 'location:activity_detail' post.event.id %}" class="btn btn-sm btn-primary w-100">
                        查看活动详情
                    </a>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</div>
<!-- 在 body 结束前添加举报模态框 -->
<div class="modal fade" id="reportModal" tabindex="-1" aria-labelledby="reportModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reportModalLabel">
                    <i class="fas fa-flag me-2"></i>举报帖子
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="reportForm">
                    {% csrf_token %}
                    <input type="hidden" id="reportPostId" value="{{ post.id }}">

                    <div class="mb-3">
                        <label for="reportReason" class="form-label">举报原因</label>
                        <select class="form-select" id="reportReason" required>
                            <option value="">请选择举报原因</option>
                            <option value="垃圾广告">垃圾广告</option>
                            <option value="虚假信息">虚假信息</option>
                            <option value="色情内容">色情内容</option>
                            <option value="暴力内容">暴力内容</option>
                            <option value="骚扰辱骂">骚扰辱骂</option>
                            <option value="违法信息">违法信息</option>
                            <option value="其他原因">其他原因</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="reportDescription" class="form-label">详细说明（可选）</label>
                        <textarea class="form-control" id="reportDescription" rows="3"
                                  placeholder="请详细描述举报原因..."></textarea>
                    </div>

                    <div class="alert alert-info">
                        <small>
                            <i class="fas fa-info-circle me-1"></i>
                            系统会自动检测帖子内容，如果包含违禁词将立即处理
                        </small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="submitReport()">
                    <i class="fas fa-flag me-1"></i>提交举报
                </button>
            </div>
        </div>
    </div>
</div>
<script>
// 点赞帖子
async function togglePostLike(postId) {
    if (!{% if user.is_authenticated %}true{% else %}false{% endif %}) {
        alert('请先登录');
        return;
    }

    try {
        const response = await fetch(`/location/community/post/${postId}/like/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            const likeIcon = document.getElementById('likeIcon');
            const likeCount = document.getElementById('likeCount');
            const likeButton = document.getElementById('likeButton');

            if (result.liked) {
                likeIcon.classList.add('text-danger');
                likeButton.classList.add('btn-danger');
                likeButton.classList.remove('btn-outline-danger');
            } else {
                likeIcon.classList.remove('text-danger');
                likeButton.classList.remove('btn-danger');
                likeButton.classList.add('btn-outline-danger');
            }
            likeCount.textContent = result.likes_count;
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// 添加评论
async function addComment(event, postId) {
    event.preventDefault();

    const form = event.target;
    const content = form.content.value.trim();

    if (!content) return;

    try {
        const formData = new FormData(form);

        const response = await fetch(`/location/community/post/${postId}/comment/`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            form.reset();
            location.reload(); // 简单重新加载页面
        } else {
            alert('评论失败：' + result.message);
        }
    } catch (error) {
        alert('评论失败：网络错误');
        console.error('Error:', error);
    }
}

// 点赞评论
async function likeComment(commentId) {
    if (!{% if user.is_authenticated %}true{% else %}false{% endif %}) {
        alert('请先登录');
        return;
    }

    try {
        const response = await fetch(`/location/community/comment/${commentId}/like/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            const likeCount = document.getElementById(`commentLikeCount-${commentId}`);
            if (likeCount) {
                likeCount.textContent = result.likes_count;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// 回复评论
function replyToComment(commentId, username) {
    // 隐藏其他回复表单
    document.querySelectorAll('.reply-form').forEach(form => {
        form.classList.add('d-none');
    });

    const replyForm = document.getElementById(`replyForm-${commentId}`);
    replyForm.classList.remove('d-none');

    // 聚焦到回复框
    const textarea = replyForm.querySelector('textarea');
    textarea.focus();
    textarea.value = `@${username} `;
}

// 取消回复
function cancelReply(commentId) {
    const replyForm = document.getElementById(`replyForm-${commentId}`);
    replyForm.classList.add('d-none');
}

// 添加回复
async function addReply(event, postId, commentId) {
    event.preventDefault();

    const form = event.target;
    const content = form.content.value.trim();

    if (!content) return;

    try {
        const formData = new FormData(form);
        formData.append('parent_id', commentId);

        const response = await fetch(`/location/community/post/${postId}/comment/`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            form.reset();
            location.reload();
        } else {
            alert('回复失败：' + result.message);
        }
    } catch (error) {
        alert('回复失败：网络错误');
        console.error('Error:', error);
    }
}

// 删除评论（异步刷新版本）
async function deleteComment(commentId) {
    if (!confirm('确定要删除这条评论吗？')) {
        return;
    }

    try {
        const response = await fetch(`/location/community/comment/${commentId}/delete/`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const result = await response.json();

        if (result.success) {
            // 删除评论元素
            const commentElement = document.getElementById(`comment-${commentId}`);
            if (commentElement) {
                commentElement.remove();
            }

            // 异步更新评论计数
            updateCommentsCount();

            // 显示成功消息
            showMessage('评论删除成功', 'success');
        } else {
            alert('删除失败：' + result.message);
        }
    } catch (error) {
        alert('删除失败：网络错误');
        console.error('Error:', error);
    }
}

// 更新评论计数
function updateCommentsCount() {
    // 计算所有评论和回复的数量
    const commentsCount = document.querySelectorAll('.comment-item, .reply-item').length;

    // 更新评论徽章
    const countElement = document.querySelector('#commentsSection .badge');
    if (countElement) {
        countElement.textContent = commentsCount;
    }

    // 更新帖子头部的评论计数
    const totalCommentsElement = document.getElementById('totalCommentsCount');
    if (totalCommentsElement) {
        totalCommentsElement.textContent = commentsCount;
    }
}

// 显示消息提示
function showMessage(message, type = 'success') {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;

    // 在评论区域顶部显示消息
    const commentsSection = document.getElementById('commentsSection');
    const commentForm = commentsSection.querySelector('.comment-form');
    if (commentForm) {
        commentForm.insertAdjacentHTML('beforebegin', alertHtml);
    } else {
        commentsSection.querySelector('.card-body').insertAdjacentHTML('afterbegin', alertHtml);
    }

    // 3秒后自动消失
    setTimeout(() => {
        const alert = document.querySelector('.alert');
        if (alert) {
            alert.remove();
        }
    }, 3000);
}

// 关注用户
async function toggleFollow(userId) {
    try {
        const response = await fetch(`/location/social/follow/${userId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            const followButton = document.getElementById('followButton');
            if (result.following) {
                followButton.innerHTML = '<i class="fas fa-check me-2"></i>已关注';
                followButton.classList.remove('btn-primary');
                followButton.classList.add('btn-success');
            } else {
                followButton.innerHTML = '<i class="fas fa-plus me-2"></i>关注';
                followButton.classList.remove('btn-success');
                followButton.classList.add('btn-primary');
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// 工具函数
function scrollToComments() {
    document.getElementById('commentsSection').scrollIntoView({ behavior: 'smooth' });
}

function sharePost() {
    const url = window.location.href;
    navigator.clipboard.writeText(url).then(() => {
        alert('链接已复制到剪贴板');
    });
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
// 举报帖子
function reportPost(postId) {
    // 检查是否是自己的帖子
    const currentUserId = {% if user.is_authenticated %}{{ user.id }}{% else %}null{% endif %};
    const postAuthorId = {{ post.author.id }};

    if (currentUserId === postAuthorId) {
        showReportResult('warning', '不能举报自己的帖子！', false);
        return;
    }

    // 检查是否登录
    if (!currentUserId) {
        showReportResult('warning', '请先登录后再进行举报！', false);
        return;
    }

    // 重置表单
    document.getElementById('reportReason').value = '';
    document.getElementById('reportDescription').value = '';

    // 显示模态框
    const reportModal = new bootstrap.Modal(document.getElementById('reportModal'));
    reportModal.show();
}

// 提交举报
async function submitReport() {
    const postId = document.getElementById('reportPostId').value;
    const reason = document.getElementById('reportReason').value;
    const description = document.getElementById('reportDescription').value;

    // 再次检查是否是自己的帖子（防止绕过前端检查）
    const currentUserId = {% if user.is_authenticated %}{{ user.id }}{% else %}null{% endif %};
    const postAuthorId = {{ post.author.id }};
    if (currentUserId === postAuthorId) {
        showReportResult('warning', '不能举报自己的帖子！', false);
        return;
    }
    if (!reason) {
        alert('请选择举报原因');
        return;
    }

    const submitBtn = document.querySelector('#reportModal .btn-danger');
    const originalText = submitBtn.innerHTML;

    // 显示加载状态
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>提交中...';
    submitBtn.disabled = true;

    try {
        const formData = new FormData();
        formData.append('reason', `${reason}${description ? ' - ' + description : ''}`);

        const response = await fetch(`/location/community/post/${postId}/report/`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        const result = await response.json();

        // 关闭模态框
        const reportModal = bootstrap.Modal.getInstance(document.getElementById('reportModal'));
        reportModal.hide();

        if (result.status === 'success') {
            // 根据检测结果显示不同的消息
            if (result.violation_found) {
                showReportResult('success', result.message, true);
            } else {
                showReportResult('info', result.message, false);
            }
        } else {
            showReportResult('error', result.message, false);
        }

    } catch (error) {
        console.error('Error:', error);
        showReportResult('error', '举报失败：网络错误', false);
    } finally {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    }
}

// 显示举报结果
function showReportResult(type, message, isViolation) {
    const alertClass = type === 'success' ? 'alert-success' :
                      type === 'info' ? 'alert-info' :
                      type === 'warning' ? 'alert-warning' : 'alert-danger';

    const icon = type === 'success' ? 'fa-check-circle' :
                type === 'info' ? 'fa-info-circle' :
                type === 'warning' ? 'fa-exclamation-circle' : 'fa-exclamation-triangle';

    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert" style="position: fixed; top: 100px; right: 20px; z-index: 9999; min-width: 300px;">
            <div class="d-flex align-items-center">
                <i class="fas ${icon} me-2"></i>
                <div class="flex-grow-1">
                    <strong>${isViolation ? '🎯 违规内容已识别' : type === 'warning' ? '⚠️ 操作提示' : '📝 举报已提交'}</strong>
                    <div class="small mt-1">${message}</div>
                </div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    // 移除现有的提示
    const existingAlert = document.querySelector('.alert[style*="position: fixed"]');
    if (existingAlert) {
        existingAlert.remove();
    }

    document.body.insertAdjacentHTML('beforeend', alertHtml);

    // 5秒后自动消失
    setTimeout(() => {
        const alert = document.querySelector('.alert[style*="position: fixed"]');
        if (alert) {
            alert.remove();
        }
    }, 5000);
}

// 删除帖子
function deletePost(postId) {
    if (confirm('确定要删除这个帖子吗？此操作不可恢复。')) {
        fetch(`/location/community/post/${postId}/delete/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert(data.message);
                window.location.href = data.redirect_url;
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败：网络错误');
        });
    }
}
</script>

<style>
.post-content {
    line-height: 1.8;
    font-size: 1.1rem;
}

.post-content img {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
}

.comment-item:last-child {
    border-bottom: none !important;
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
}

.reply-item {
    border-left: 3px solid #e9ecef !important;
}

.smaller {
    font-size: 0.8rem;
}

.breadcrumb {
    background: none;
    padding: 0;
    margin-bottom: 1rem;
}
</style>
{% endblock %}